import cv2
import os

def imgs_seek(start_path):
    photo_list = []  # 图片列表
    def imgs_seek():
        os.chdir(start_path)  # 查找图片的途径
        items = os.listdir(os.curdir)  # 该路径下所有文件
        photo_type = ['.jpg', '.png', 'jpeg']  # 添加查找图片的格式   注意加.  如'.JPG'
        for each in items:
            if os.path.splitext(each)[1].lower() in photo_type:
                photo_list.append(os.getcwd() + os.sep + each)
            if os.path.isdir(each):
                imgs_seek(each)  # 递归函数查找下一目录下的文件
                os.chdir(os.pardir)  # 返回上一层文件目录
        return photo_list
    imgs_seek()
    return photo_list


def resize_width(img, width_resize, taget_height):
    taget_img = cv2.resize(img, None, fx=width_resize, fy=width_resize)
    # print(taget_img.shape)
    # cv2.imshow('taget_img', taget_img)
    # cv2.waitKey(0)
    if (int(taget_height) - int(taget_img.shape[1])) % 2:
        fix_height = int((int(taget_height) - int(taget_img.shape[1])) / 2)
        taget_img = cv2.copyMakeBorder(taget_img, 0, 0, fix_height + 1, fix_height, cv2.BORDER_CONSTANT, value=(255, 255, 255))
    else:
        fix_height = int((int(taget_height) - int(taget_img.shape[1])) / 2)
        taget_img = cv2.copyMakeBorder(taget_img, 0, 0, fix_height, fix_height, cv2.BORDER_CONSTANT, value=(255, 255, 255))
    return taget_img


def resize_height(img, height_resize, taget_width):
    taget_img = cv2.resize(img, None, fx=height_resize, fy=height_resize)
    # print(taget_img.shape)
    if (int(taget_width) - int(taget_img.shape[0])) % 2:
        fix_width = int((int(taget_width) - int(taget_img.shape[0])) / 2)
        taget_img = cv2.copyMakeBorder(taget_img,fix_width + 1, fix_width, 0, 0,  cv2.BORDER_CONSTANT, value=(255, 255, 255))
    else:
        fix_width = int((int(taget_width) - int(taget_img.shape[0])) / 2)
        taget_img = cv2.copyMakeBorder(taget_img,fix_width, fix_width, 0, 0,  cv2.BORDER_CONSTANT, value=(255, 255, 255))
    return taget_img


def img_resize(img_path, save_path, img_name, taget_size):
    taget_width, taget_height = taget_size  # 一般情况下可视为taget_size为正方形
    img = cv2.imread(img_path)
    width = img.shape[0]
    height = img.shape[1]
    width_resize = float(taget_width / width)
    height_resize = float(taget_height / height)
    #宽度大于高度的图片
    if width_resize > height_resize:
        taget_img = resize_height(img, height_resize, taget_width)
    #高度大于宽度的图片
    else:
        taget_img = resize_width(img, width_resize, taget_width)
    cv2.imwrite(save_path + '\\' + img_name + '.jpg', taget_img)

if __name__ == '__main__':
    imgs_path = r'C:\Users\Administrator\Desktop\imgs'
    save_path = r'C:\Users\Administrator\Desktop\resize'
    taget_size = (416.0, 416.0)  #目标尺寸
    imgs = imgs_seek(imgs_path)
    for img_path in imgs:
        img_name = (img_path.split('.'))[0].split('\\')[-1]
        img_resize(img_path, save_path, img_name, taget_size)


